package com.neusoft.dao;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.neusoft.model.Admin;
import com.neusoft.model.UmsAdminLoginLog;
import org.junit.Test;

/*	Dao类主要跟数据库打交道
 * 		负责数据库的增删改查
 * 	JavaBean
 * 		一般与数据库表结构一致，一般放在model或entity包中
 */
public class AdminDao extends BaseDao<Admin> {

	public boolean insert(Admin bean) {
		String sql = "insert into ums_admin(id, username, password, icon, email, nick_name, note, create_time, login_time, status) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
		return doIUD(sql, bean.getId(), bean.getUsername(), bean.getPassword(), bean.getIcon(), bean.getEmail(),
				bean.getNickName(), bean.getNote(), bean.getCreateTime(), bean.getLoginTime(), bean.getStatus());
	}

	public boolean update(Admin bean) {
		String sql = "update ums_admin set password = ?, status = ?, create_time = ? where id = ?";
		return doIUD(sql, bean.getPassword(), bean.getStatus(), bean.getCreateTime(), bean.getId());
	}

	public boolean delete(int id) {
		String sql = "delete from ums_admin where id = ?";
		return doIUD(sql, id);
	}
	
	/*	查询方法
	 * 		1、查询多条
	 * 		2、查询单条
	 */
	public Admin getById(Integer id) {
		Connection conn = getConn();
		String sql = "select * from ums_admin where id = ?";
		PreparedStatement st = null;//可以防止sql注入攻击
		ResultSet rs = null;
		Admin bean = null;
		try {
			//通过数据库连接conn获取事务java.sql.Statement对象st
			st = conn.prepareStatement(sql);
			st.setObject(1, id);
			//执行sql命令
			rs = st.executeQuery(sql);
			//处理查询结果集
			if(rs.next()) {
				bean = new Admin();
				bean.setId(rs.getLong("id"));
				bean.setUsername(rs.getString("username"));
				bean.setPassword(rs.getString("password"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(rs, st, conn);
		}
		
		return bean;
	}
	
	@Test
	public void getList() {
		String sql = "select * from ums_admin";
		List<Admin> list = new ArrayList<Admin>();
		query(sql, Admin.class, list);
		System.out.println(list);
	}

	@Test
	public void t1() {
		String sql = "select * from ums_admin where id = ?";
		Admin admin = query(sql, Admin.class, null, 1);
		System.out.println(admin);
	}
}
